package org.fast.develop.logicflow.springboot.configuration;

import org.fast.develop.logicflow.core.LogicFlowConfiguration;
import org.fast.develop.logicflow.runtime.LogicFlowExecutor;
import org.fast.develop.logicflow.runtime.LogicFlowRuntimeConfiguration;
import org.fast.develop.logicflow.runtime.cache.IThreadStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * @author 莫寅
 * @createTime 2022-11-25 13:03
 * @desc：
 */
@Configuration
public class LogicFlowRuntimeAutoConfiguration {


    private IThreadStore threadStore;

    @Autowired
    public void setThreadStore(@Lazy IThreadStore threadStore) {
        this.threadStore = threadStore;
    }

    @Bean
    public LogicFlowRuntimeConfiguration logicFlowRuntimeConfiguration(
            @Autowired(required = false) LogicFlowElementRegistor logicFlowElementRegistor,
            @Autowired ApplicationContext applicationContext
    ) {
        SpringTaskListenerCreator springTaskListenerCreator = new SpringTaskListenerCreator(applicationContext);
        LogicFlowConfiguration logicFlowConfiguration = new LogicFlowConfiguration();


        LogicFlowRuntimeConfiguration logicFlowRuntimeConfiguration = new LogicFlowRuntimeConfiguration(springTaskListenerCreator, logicFlowConfiguration, threadStore);

        if (logicFlowElementRegistor != null) {
            logicFlowElementRegistor.getElement().forEach((s, aClass) -> {
                logicFlowConfiguration.registerElement(s, aClass);
            });
        }

        return logicFlowRuntimeConfiguration;
    }

    @Bean
    public LogicFlowExecutor logicFlowExecutor(LogicFlowRuntimeConfiguration logicFlowRuntimeConfiguration) {
        return logicFlowRuntimeConfiguration.getLogicFlowExecutor();
    }

}
